window.onload = function() {
    // 动态样式
    let sidebarUl = document.querySelector('.sidebar ul')
    let contentOl = document.querySelector('.content ol')
    let footer = document.querySelector('.footer')
    sidebarUl.style.height = document.documentElement.clientHeight - footer.offsetHeight - sidebarUl.offsetTop + 'px'
    contentOl.style.height = document.documentElement.clientHeight - footer.offsetHeight - contentOl.offsetTop + 'px'
    let content = document.querySelector('.content')
    content.style.width = document.documentElement.clientWidth - sidebarUl.offsetWidth - 40 + 'px'
    // 请求分类数据
    let catPromise = request({url: 'http://localhost:3000/front/api/cat/getall'})
    let menuPromise = request({url: 'http://localhost:3000/front/api/menus/getall'})

    Promise.all([catPromise, menuPromise]).then(arr => {
        // console.log(arr);
        let [cats, menus] = arr
        // 渲染分类
        var {error_code, msg} = cats
        if(error_code == 0) {
            var cathtml = ''
            cats.data.forEach(item => {
                cathtml += `<li>${item.catname}</li>`
            })
            sidebarUl.innerHTML = cathtml
        }
        // 渲染商品
        renderMenus(menus, contentOl)
    })

    // 点击选规格
    var mask = document.querySelector('.mask')
    var img = mask.querySelector('.detail>img')
    var h4 = mask.querySelector('.detail>h4')
    var speces = mask.querySelector('.spec')
    var kinds = mask.querySelector('.kind')
    var addcartBtn = document.querySelector('.addcart')
    // 点击选规格
    contentOl.onclick = e => {
        var target = e.target
        if(target.tagName === 'INPUT' && target.type === 'button') {
            // 图片显示
            img.src = target.previousElementSibling.previousElementSibling.previousElementSibling.src
            // 获取规格和种类数据
            let {spec, kind, id} = target.dataset
            // 添加购物车按钮上放商品id
            addcartBtn.setAttribute('data-id', id)
            // 规格 
            var speceshtml = ''
            // 渲染规格
            spec.split('=====').forEach(item => {
                speceshtml += `
                    <p>${item}</p>
                `
            })
            speces.innerHTML = speceshtml
            speces.children[0].className = 'active'
            // 种类
            var kindshtml = ''
            // 渲染种类
            kind.split('=====').forEach(item => {
                kindshtml += `
                    <p>${item}</p>
                `
            })
            kinds.innerHTML = kindshtml
            kinds.children[0].className = 'active'
            // 遮罩显示
            mask.style.display = 'block'
        }
    }
    // 切换规格
    speces.onclick = spedAndKindTab
    kinds.onclick = spedAndKindTab

    // 关闭遮罩
    var closeBtn = document.querySelector('.close')
    closeBtn.onclick = e => {
        mask.style.display = 'none'
    }

    // 搜索功能
    var searchForm = document.querySelector('.search form')
    var keywords = document.querySelector('[name="keywords"]')
    searchForm.onsubmit = e => {
        request({
            url: 'http://localhost:3000/front/api/menus/search/' + keywords.value
        }).then(menus => renderMenus(menus, contentOl))
        return false
    }

    // 添加购物车
    // 获取底部购物车页面
    var cartBox = document.querySelector('.cart')
    addcartBtn.onclick = function(e) {
        // 判断用户是否登录
        // let userid = getCookie('userid')
        let userid=localStorage.getItem('userid')
        console.log(userid);
        if(!userid) {
            popup.msg('请先登录！', () => {
                // 保存当前地址
                localStorage.setItem('url', location.href)
                // 强制跳转到登录
                location.href = './login.html'
            })
            
            return false
        }
        // 获取选中的规格
        let spec = document.querySelector('.spec p.active').innerText
        // 获取选中的种类
        let kind = document.querySelector('.kind p.active').innerText
        // 组合添加购物车需要的规格和种类
        let speandkind = spec + ',' + kind
        request({
            method: 'post',
            url: 'http://localhost:3000/front/api/cart/add',
            data: {
                userid,
                menuid: this.dataset.id,
                num: 1,
                speandkind
            },
            headers: {
                authorization: localStorage.getItem('token')
            }
        }).then(res => {
            let {error_code, msg} = res
            if(error_code === 0) {
                popup.msg(msg, () => {
                    mask.style.display = 'none'
                    // 让底部购物车显示
                    cartBox.style.display = 'flex'
                    return request({
                        url: 'http://localhost:3000/front/api/cart/count',
                        headers: {
                            authorization: localStorage.getItem('token')
                        }
                    }).then(res => {
                        console.log(res);
                        document.querySelector('.cartnum').innerText = res.data
                        // console.log(res);
                    })
                })
            }
            
        })
    }

    // // 结算
    // var settleBtn = document.querySelector('.settle')
    // settleBtn.onclick = e => {
        
    // }

    // 底部导航
    var footerNav = document.querySelectorAll('.footer>div')
    for(var a = 0; a < footerNav.length; a++) {
        footerNav[a].onclick = function() {
            location.href = this.dataset.url
        }
    }
    
   
}
// 封装规格和种类切换函数
function spedAndKindTab(e) {
    target = e.target
    if(target.tagName === 'P') {
        for(var a = 0; a < this.children.length; a++) {
            this.children[a].className = ''
        }
        target.className = 'active'
    }
}

// 封装渲染商品的函数
function renderMenus(menus, contentOl) {
    var {error_code, msg} = menus
    if(error_code == 0) {
        var menuhtml = ''
        menus.data.forEach(item => {
            menuhtml += `
            <li>
                <img src="${item.imgpath}" alt="">
                
                <i>￥${item.name}</i>
                <span>￥${item.price}</span>
                <input data-kind="${item.kind}" data-spec="${item.specifications}" type="button" data-id="${item._id}" value="选规格">
                <b>1</b>
            </li>
            `
        })
        contentOl.innerHTML = menuhtml
    }
}